<script setup>
import {reactive, ref,onMounted,nextTick} from 'vue'
import {get,post}  from '@/myaxios'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import router from '@/router'


//table展示使用的数据
const tableData = reactive({tableList:[],
                            pageInfo:{
                                page:2,
                                pageSize:20,
                                total:75
                            }
})

//查询表单数据
const queryForm  = reactive({
    menuname:'',
    pid:''
})
//pid下拉列表数据
//图标下拉列表
const menuSelect = reactive({menuList:[],
                             iconList:[]
})

//查询表单组件对象
const queryFormRef = ref()

//重置查询条件并查询
const onQueryReset = ()=>{
    queryFormRef.value.resetFields()
    queryData({})
}

//点击查询按钮查询
const onQuerySubmit = ()=>{
    queryData(queryForm)
}

//点击页码查询
const handleCurrentChange = (pageNum)=>{
    console.log(pageNum);
    //改当前的page
    tableData.pageInfo.page = pageNum;
    //把pageInfo对象发送给后端
    //tableData.pageInfo  queryForm
    //多个json对象组合成一个 {...json对象,...json对象2 }
    let allParam ={...tableData.pageInfo,...queryForm}
    queryData(allParam)
}
//点击pageSize下拉列表查询
const handleSizeChange = (pageSizeNum)=>{
    console.log(pageSizeNum);
    //改当前的page
    tableData.pageInfo.page = 1;
    tableData.pageInfo.pageSize = pageSizeNum;
    //把pageInfo对象发送给后端
    //多个json对象组合成一个 {...json对象,...json对象2 }
    let allParam ={...tableData.pageInfo,...queryForm}
    queryData(allParam)



}

/* 添加功能*/
/**
 * 弹出框处理流程
 * 
 * 1 添加触发弹窗的按钮
 * 2 添加弹出框  dialog组件
 * 3 设置 控制弹窗显示/隐藏的bol值
 * 
 * 4 设置弹窗包含的内容 表单 表格 其他数据
 * 5 如果是表单 设置表单的数据 表单的样式 
 * 
 * 6 提交动作时 关框 提交数据 处理相应反馈 
 * 
 */

//控制弹窗显示/隐藏
const addDialogVisible = ref(false)

//添加使用的表单数据对象
const addForm = reactive({
    mid:'',
    menuname:'',
    pid:'',
    url:'',
    glyphicon:''
})

//添加表单对象
const addFormRef = ref()


//打开弹出框
const openAddDialog = ()=>{
    

    //打开弹出框
    addDialogVisible.value = true

    //vue机制 虚拟dom
    //弹出框 默认不渲染 需要显示时才渲染 包含关联的数据对象
    
    //清除表单数据
    // if(addFormRef.value !=undefined){
    //     addFormRef.value.resetFields()
    // }

    //从侧面控制代码执行顺序
    //延迟渲染
    nextTick(()=>{
        console.log(11111);
        addFormRef.value.resetFields()
    })



}

//弹出框提交
const addDialogSubmit = async ()=>{
    //关框
    addDialogVisible.value = false

   // console.log('通过ajax请求 把数据传给后端',addForm );
    //提交请求
    operationData("/menus/addMenu",addForm)


}

//*修改功能*/
//修改数据表单
//修改时 这个updateForm 需要被后端数据覆盖   为了保持响应式变量 需要多加一个key updateData
//      比如addForm    不需要被后端数据覆盖  不需要多加key
const updateForm = reactive({updateData:{
    mid:'',
    menuname:'',
    pid:'',
    url:'',
    glyphicon:''
}})


//控制修改框显示/隐藏
const updateDialogVisible = ref(false)
//修改框开框 加载数据
const openUpdateDialog = async (rowData)=>{
    updateDialogVisible.value = true 
    console.log(rowData);
    let resp = await post("/menus/getMenuById",{mid:rowData.mid})
    console.log(resp.data.returnData);
    //把查出的修改对象 填充给form上的默认对象
    updateForm.updateData = resp.data.returnData
    
}
//修改提交
const updateDialogSubmit = async ()=>{
    //关框
    updateDialogVisible.value = false
    //提交请求
    operationData("/menus/updateMenu",updateForm.updateData)



}

/**删除功能 */
const openDeleteDialog = (mid)=>{
    console.log(mid);

    ElMessageBox.confirm(
    `是否删除编号为 [${mid}] 的数据?`,
    '注意',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        //提交请求
        operationData("/menus/deleteMenu",{'mid':mid})
    })
    .catch(() => {
        //啥都不干
    })

}

//table组件(如果需要调用UI库中 table组件的内置方法 需要获得组件)
const tableRef = ref()

//多条删除
const openDeleteMultipleDialog = ()=>{
    let currentRows = tableRef.value.getSelectionRows()
    if(currentRows.length == 0){
        ElMessage.warning('请选择数据')
    }else{
        console.log(currentRows);
        let listMidArr = [];
        currentRows.forEach(menuData=>{
            listMidArr.push(menuData.mid)  
        })
        let listMidStr = listMidArr.join(',')
        console.log('发送ajax请求',listMidStr);

        //弹窗提示 是否删除

        ElMessageBox.confirm(
            `是否删除编号为 [${listMidStr}] 的数据?`,
            '注意',
            {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
            }
        )
            .then(() => {
                //提交请求
                operationData("/menus/deleteMenuMultiple",{'listMid':listMidStr})
            })
            .catch(() => {
                //啥都不干
            })
    }

    //getSelectionRows
    
}



/**
 * 公共函数
 * 
 */

//查询一级菜单下拉列表
const queryMenuLevel1 = async () => {
   let resp = await  get("/menus/listSelect",{})
   menuSelect.menuList = resp.data.returnData

}
//查询菜单可用图标
const listIcon = async()=>{
    let resp = await get("/menus/listIcon",{})
    menuSelect.iconList = resp.data.returnData
}

//查询函数
const queryData = async (params)=>{
//异步调用的同步控制  
//async 异步开启同步控制 await 异步同步的等待
//异步操作 ajax请求
//        定时函数 
    
    //有await修饰的ajax请求 必须拿到响应之后才能向下执行
    let resp =  await get("/menus/listMenu",params)
    //(这里以下的代码 必须是得到响应后才会执行)
    console.log(resp.data);
    if(resp.data.code == 2000){
        //查到数据的处理
        tableData.tableList = resp.data.returnData
        tableData.pageInfo = resp.data.pageInfo
    }else if(resp.data.code == 2001){
        //查不到数据的处理
        tableData.tableList = []
        tableData.pageInfo = {page:1,pageSize:10,total:0}
    }

    //异步请求
    //回调地狱
    // get("/listMenu",params)
    // .then(resp=>{
    //     console.log(1111);
    //     console.log(resp.data);
    //     if(resp.data.code == 2000){
    //         //查到数据的处理
    //         tableData.tableList = resp.data.returnData
    //         tableData.pageInfo = resp.data.pageInfo
    //     }else if(resp.data.code == 2001){
    //         //查不到数据的处理
    //         tableData.tableList = []
    //         tableData.pageInfo = {page:1,pageSize:10,total:0}
    //     }
    // })
    // console.log(2222);

    


}

//添加修改删除
const operationData = async(url,params)=>{
    
   // console.log('通过ajax请求 把数据传给后端',addForm );
   let resp = await post(url,params)
   console.log(resp.data);
   //1 弹消息 操作结果
   //2 刷新table数据
   if(resp.data.code == 2010){
        ElMessage.success(resp.data.msg)
   }else if(resp.data.code == 2011){
        ElMessage.error(resp.data.msg)
   }
   //重新查询
   //queryData({})
   //用当前条件查
   let allParam ={...tableData.pageInfo,...queryForm}
   queryData(allParam)
   //刷新下拉列表数据
   queryMenuLevel1()
}


//页面加载结束 初始化页面
onMounted(()=>{
    queryData({})
    queryMenuLevel1()
    listIcon()
})


/**
 * 普通使用ajax请求
 * 
 * const queryData = async (params)=>{
*      get("/listMenu",params)
        .then(resp=>{
            console.log(1111);
            console.log(resp.data);
            if(resp.data.code == 2000){
                //查到数据的处理
                tableData.tableList = resp.data.returnData
                tableData.pageInfo = resp.data.pageInfo
            }else if(resp.data.code == 2001){
                //查不到数据的处理
                tableData.tableList = []
                tableData.pageInfo = {page:1,pageSize:10,total:0}
            }
        })
 * 
 * }
 * 
 * 使用await
 * const queryData = async (params)=>{
 *      let resp =  await get("/listMenu",params)
        console.log(resp.data);
        if(resp.data.code == 2000){
            //查到数据的处理
            tableData.tableList = resp.data.returnData
            tableData.pageInfo = resp.data.pageInfo
        }else if(resp.data.code == 2001){
            //查不到数据的处理
            tableData.tableList = []
            tableData.pageInfo = {page:1,pageSize:10,total:0}
        }
 * 
 * }
 * 
 */


</script>

<template>

<el-form ref="queryFormRef" :inline="true" :model="queryForm" >
    <el-form-item label="菜单名称" prop="menuname">
      <el-input v-model="queryForm.menuname" style="width: 240px;" placeholder="menuname" clearable />
    </el-form-item>
    <el-form-item label="上级编号" prop="pid">
      <!-- <el-input v-model="queryForm.pid" style="width: 240px;" placeholder="pid" clearable /> -->
      
      <el-select
        v-model="queryForm.pid"
        style="width: 240px;"
        placeholder="pid"
        clearable>
        <el-option value="0" label="无" >0-无</el-option>
        <el-option v-for="option in menuSelect.menuList" :value="option.mid" :label="option.menuname">{{option.mid+"-"+option.menuname}}</el-option>
      </el-select>
    
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="onQuerySubmit">查询</el-button>
      <el-button  plain @click="onQueryReset">重置</el-button>
      <el-button  type="primary" plain @click="openAddDialog">添加</el-button>
      <el-button  type="danger" plain @click="openDeleteMultipleDialog">删除</el-button>
    </el-form-item>
  </el-form>


  <el-table ref="tableRef" :data="tableData.tableList" height="480" style="width: 100%">
    <el-table-column fixed type="selection"  width="55" />
    <el-table-column fixed  prop="mid" label="编号"  />
    <el-table-column prop="menuname" label="名称"  />
    <el-table-column prop="pid" label="上级编号"  >
        <template #default="scope">
            <el-text v-if="scope.row.pid == 0" type="success">{{ scope.row.pid }}</el-text>
            <el-text v-else type="warning">{{ scope.row.pid }}</el-text>
        </template>
    </el-table-column>
    <el-table-column prop="pname" label="上级名称" width="180" >
        <template #default="scope">
            <el-text v-if="scope.row.pid == 0" type="success">{{ scope.row.pname }}</el-text>
            <el-text v-else type="warning">{{ scope.row.pname }}</el-text>

        </template>
    </el-table-column>
    <el-table-column prop="url" label="访问路径" width="180" />
    <el-table-column prop="glyphicon" label="图标" >
        <template #default="scope">
            <!-- 图标标签错误 会导致页面报错  -->
            <el-tag type="primary"><el-icon> <component :is="scope.row.glyphicon"/> </el-icon></el-tag>
            <el-tag type="primary">{{ scope.row.glyphicon }}</el-tag> 
        </template>

    </el-table-column>
    <el-table-column label="操作" width="180" >
        <template #default="scope">
            <el-button  type="warning" plain @click="openUpdateDialog(scope.row)">修改</el-button>
            <!-- <el-button  type="danger" plain @click="openDeleteDialog(scope.row.mid)">删除</el-button> -->
        </template>
        
    </el-table-column>

  </el-table>

  <el-pagination
      v-model:current-page="tableData.pageInfo.page"
      v-model:page-size="tableData.pageInfo.pageSize"
      :total="tableData.pageInfo.total"
      :page-sizes="[10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      
    />


    <el-dialog
        v-model="addDialogVisible"
        title="添加"
        width="500">
        <el-form  ref="addFormRef" :model="addForm" label-width="80" style="max-width: 600px">
            <el-form-item label="菜单编号" prop="mid">
                <el-input v-model="addForm.mid" />
            </el-form-item>
            <el-form-item label="菜单名称" prop="menuname">
                <el-input  v-model="addForm.menuname"/>
            </el-form-item>
            <el-form-item label="上级编号" prop="pid">
                <!-- <el-input  v-model="addForm.pid"/> -->
                <el-select
                    v-model="addForm.pid"
                    style="width: 100%;"
                    
                    >
                    <el-option value="0" label="无" >0-无</el-option>
                    <el-option v-for="option in menuSelect.menuList" :value="option.mid" :label="option.menuname">{{option.mid+"-"+option.menuname}}</el-option>
                </el-select>


            </el-form-item>
            <el-form-item label="访问路径" prop="url">
                <el-input  v-model="addForm.url"/>
            </el-form-item>
            <el-form-item label="菜单图标" prop="glyphicon">
                <!-- <el-input  v-model="addForm.glyphicon"/> -->
                <el-select
                    v-model="addForm.glyphicon"
                    style="width: 100%;"
                    
                    >
                    <el-option v-for="iconName in menuSelect.iconList" :value="iconName" :label="iconName"><el-icon><component :is="iconName"/></el-icon> {{iconName}}</el-option>
                </el-select>


            </el-form-item>
        </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addDialogSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog
        v-model="updateDialogVisible"
        title="修改"
        width="500">
        <el-form   :model="updateForm.updateData" label-width="80" style="max-width: 600px">
            <el-form-item label="菜单编号" prop="mid">
                <el-input v-model="updateForm.updateData.mid" disabled />
            </el-form-item>
            <el-form-item label="菜单名称" prop="menuname">
                <el-input  v-model="updateForm.updateData.menuname"/>
            </el-form-item>
            <el-form-item label="上级编号" prop="pid">
                
                <el-select
                    v-model="updateForm.updateData.pid"
                    style="width: 100%;"
                    >
                    <el-option :value="0" label="无" >0-无</el-option>
                    <el-option v-for="option in menuSelect.menuList" :value="option.mid" :label="option.menuname">{{option.mid+"-"+option.menuname}}</el-option>
                </el-select>


            </el-form-item>
            <el-form-item label="访问路径" prop="url">
                <el-input  v-model="updateForm.updateData.url"/>
            </el-form-item>
            <el-form-item label="菜单图标" prop="glyphicon">
                
                <el-select
                    v-model="updateForm.updateData.glyphicon"
                    style="width: 100%;"
                    >
                    <el-option v-for="iconName in menuSelect.iconList" :value="iconName" :label="iconName"><el-icon><component :is="iconName"/></el-icon> {{iconName}}</el-option>
                </el-select>
            </el-form-item>
        </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateDialogSubmit">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>



</template>

<style scoped>

</style>